package com.epam.iunna.bookshop.controller.filters;


import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.epam.iunna.bookshop.model.User;

public class AuthFilter implements Filter {
	
	public final static String USER_SESSION_KEY = "USER_SESSION_KEY";
	
	private static final Set<String> AUTH_EXCEPTION_PAGE_SET;
	static{
	    Set<String> tempSet = new HashSet<String>();
	    tempSet.add("Login");
	    tempSet.add("CreateUser");
	    tempSet.add("InputCreateUser");
	    AUTH_EXCEPTION_PAGE_SET = Collections.unmodifiableSet(tempSet);
	}
	
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest)req;
        HttpSession session = request.getSession(true);
        if( AUTH_EXCEPTION_PAGE_SET.contains( request.getParameter("cmd") )
                || session.getAttribute( USER_SESSION_KEY ) instanceof User ){
        	chain.doFilter(req, res);
        	return;
        }
        //User user = (User)session.getAttribute( USER_SESSION_KEY );
        request.getRequestDispatcher("/login.jsp").forward(req, res);
    }
    
    // @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }


	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
